package top.malaoshi.controller;

import org.springframework.web.bind.annotation.*;
import top.malaoshi.entity.Book;
import top.malaoshi.model.JsonResult;
import top.malaoshi.service.BookSrvImpl;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class BookCtrl {

    @Resource
    private BookSrvImpl bookSrv;

//    @RequestMapping("/{id}")
//    public String get(@PathVariable String id){
//        System.out.println("id:"+id);
//        return "id:"+id;
//    }

    /**
     * 根据id显示图书详细信息
     * @param aa
     * @return
     */
    @GetMapping("/book/{id}")
    public JsonResult get(@PathVariable(name="id") String aa){
        System.out.println("id:"+aa);
        //假装查询
        Book book=new Book(aa,"java从入门到放弃","李雷");

        JsonResult<Book> res=new JsonResult(0,"成功");
        res.setData(book);

//        return "id:"+aa;
        return res;
    }

    @DeleteMapping(value={"/book/{id}","/book"})
    public JsonResult deleteById(@PathVariable(required = false) String id){
        System.out.println("id:"+id);
        //假装根据id删除成功！
        return new JsonResult(0,"删除成功！");
    }

    @PostMapping("/books")
    public JsonResult list() throws Exception {
        //模拟抛运行时异常
//        int i=1/0;


        //假装查询
        Book java = new Book("1122", "23天学会JAVA", "李雷");
        Book mysql = new Book("2233", "7天学会mysql", "韩梅梅");

        List books = new ArrayList();
        books.add(java);
        books.add(mysql);

        JsonResult res = new JsonResult(0, "成功");
        res.setData(books);

//        return res;
        throw new Exception("模拟抛出非运行时异常");
    }

    @PostMapping("/book/{name}/{author}")
    public JsonResult save(@PathVariable String name,@PathVariable String author){

        JsonResult res=new JsonResult(0,"保存成功！");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        try {
            Book book = new Book(uuid, name, author);
            bookSrv.save(book);
        }catch (Exception e){
            e.printStackTrace();
            res.setCode(100);
            res.setMsg("保存失败！");
        }
        String content=String.format("name:%s,author:%s",name,author);
        System.out.println(content);

        return res;
    }
}
